package com.learner.common.response;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.learner.common.exception.RestException;
import com.learner.common.exception.RestStatus;
import com.learner.common.http.CommonCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Map;
import java.util.Objects;

/**
 * @author ice2020x
 * @Date: 2023/3/8
 * @Description: 统一结果处理
 **/
@Slf4j
@ControllerAdvice(annotations = {RestController.class, RestControllerAdvice.class})
public class RestResponseBody implements ResponseBodyAdvice<Object> {


    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object object, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        Map<String, Object> result;

        if (MediaType.TEXT_HTML.equals(selectedContentType)) {
            return object;
        }
        //若返回内容为空的时候，将空Map作为返回对象
        if (object == null) {
            object = Maps.newHashMap();
        }

        if (object instanceof RestException) {
            //返回异常
            RestException exec = ((RestException) object);
            if (!exec.isError()) {
                if (exec.getCode() != 0) {
                    log.warn("出现错误：" + exec.getMsg());
                }
            }
            result = ((RestException) object).toMap();
        } else if (object instanceof RestStatus) {
            //返回接口处理状态
            result = ((RestStatus) object).toMap();
        } else if (object instanceof byte[]) {
            //返回下载流
            return object;
        } else if (object instanceof String) {
            result = CommonCode.SUCCESS.toMap();
            //将返回的数据,封装进data中
            result.put("data", object);
            return JSON.toJSONString(result);
        } else {
            result = CommonCode.SUCCESS.toMap();
            //将返回的数据,封装进data中
            result.put("data", object);
        }

        return result;
    }
}